﻿using EnvDTE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Axiom.CodeManifold
{
	public static class CodeFunctionExtensions
	{
		public static string GetComment(this CodeFunction function)
		{
			XElement root = XElement.Parse(function.DocComment);
			var comment = (from a in root.Descendants("summary")
						   select (string)a).FirstOrDefault();

			if (string.IsNullOrWhiteSpace(comment))
			{
				comment = function.Comment;
			}

			return comment;
		}

		public static void AutoComment(this CodeFunction function)
		{
			if (!string.IsNullOrWhiteSpace(function.GetComment()))
			{
				return;
			}

			var method = new MethodDefinition(function);
			method.CreateDocComment(method.Name.SplitPascalCase());

			function.DocComment = method.DocComment;
		}

		public static string GetBody(this CodeFunction function)
		{
			vsCMElement parentkind = (vsCMElement)function.Parent.Kind;
			if (parentkind == vsCMElement.vsCMElementInterface)
			{
				return string.Empty;
			}

			var part = vsCMPart.vsCMPartBody;
			var start = function.GetStartPoint(part);
			var text = function.GetEndPoint(part).CreateEditPoint().GetText(start);

			return text;
		}

		public static string GetSignature(this CodeFunction function)
		{
			var sb = new StringBuilder();

			sb.AppendFormat("{0} {1}(", function.Type.GetTypeAsString(), function.Name);
			foreach (CodeParameter parameter in function.Parameters)
			{
				sb.AppendFormat("{0} {1}", parameter.Type.GetTypeAsString(), parameter.Name);
			}
			sb.Append(")");

			return sb.ToString();
		}
	}
}
